import React, { useState, useEffect, useRef } from 'react';
import {
  Card,
  Grid,
  Typography,
  Pagination,
  Button,
  Table,
  Space,
  Popconfirm,
  TableColumnProps,
  Message,
} from '@arco-design/web-react';
import styles from './style/index.module.less';
import useLocale from '@/utils/useLocale';
import locale from './locale';
import Lesson from '@/pages/system/course/lesson';
import {
  deleteLessonApi,
  delSysAccountApi,
  getCollegesAndMajorApi,
  getLessonsApi,
  getLessonsByPageApi,
  getMyLessonsApi,
  getSysCourseApi,
} from '@/request/api';
import LessonFormModal from './lessonFormModal';
import { useSelector } from 'react-redux';
import { DictionaryState } from '@/store/dictionary';
import { keyToValue } from '@/utils/dictionary';
import LessonDrawer from '@/pages/system/course/lessonDrawer';
import Student from '@/pages/system/course/student';
import DictionaryModal from '@/pages/system/course/dictionaryModal';
import TeacherModal from '@/pages/system/course/teacherModal';
import DetailDrawer from "./DetailDrawer";
const Row = Grid.Row;
const Col = Grid.Col;
const { Title } = Typography;

function Course() {
  const t = useLocale(locale);
  const columns: TableColumnProps[] = [
    {
      title: '课程名称',
      dataIndex: 'name',
      align: 'center',
    },
    {
      title: '所属院校/专业',
      dataIndex: 'sysDeptName',
      align: 'center',
      render: (_, record) => (
        <div>
          {' '}
          {record.sysSpecialityDeptList.map((item) => {
            return `  ${item.sysDept.name}/${item.sysSpecialityDept.name} `;
          })}
        </div>
      ),
    },
    // {
    //   title: '所属专业',
    //   dataIndex: 'sysSpecialityDeptName',
    //   align: 'center',
    // },
    {
      title: '课程教师',
      dataIndex: 'deptIds',
      ellipsis: true,
      align: 'center',
      render: (_, record) => (
        <div>
          {' '}
          {record.teacherList.map((item) => {
            return `${item.name},`;
          })}
        </div>
      ),
    },
    {
      title: '是否必修',
      dataIndex: 'required',
      align: 'center',
      render: (_, record) => <div>{`${_ === 0 ? '不必修' : '必修'}`}</div>,
    },
    {
      title: '课程类型',
      dataIndex: 'courseType',
      align: 'center',
      render: (_, record) => (
        <div>{`${keyToValue(_, dictionary.courseType)}`}</div>
      ),
    },
    {
      title: '发布教授',
      dataIndex: 'createByUser.name',
      align: 'center',
    },
    {
      title: '时间',
      dataIndex: 'updateTime',
      align: 'center',
    },
    {
      title: '操作',
      dataIndex: 'op',
      align: 'center',
      width: 220,
      render: (_, record) => (
        <Space size={'mini'}>
          <Button
            size={'mini'}
            type="outline"
            onClick={() => openMenu(record)}
          >
            查看
          </Button>

          <Button
            size={'mini'}
            type="outline"
            onClick={() => teacherClick(record)}
          >
            教师
          </Button>
          <Button
            size={'mini'}
            type="outline"
            onClick={() => teacherClick1(record)}
          >
            学生
          </Button>
          <Button
            size={'mini'}
            type="outline"
            onClick={() => editItemClick(record)}
          >
            修改
          </Button>
          <Popconfirm
            focusLock
            title="删除"
            content="确定删除?"
            onOk={() => {
              delItemClick(record.id);
            }}
          >
            <Button size={'mini'} status={'danger'} type="outline">
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  const dictionary = useSelector(
    (state: DictionaryState) => state['dictionary']
  );

  const [courses, setCourses] = useState({
    total: 0,
    list: [],
  });
  const [page, setPage] = useState({
    pageNum: 1,
    pageSize: 10,
  });
  const detailRef = useRef(null)
  const childRef = useRef(null);
  const drawerRef = useRef(null);
  const teacherRef = useRef(null);
  const studentRef = useRef(null)
  const updateChildState = () => {
    childRef.current.resetFormData();
    childRef.current.setUpdateId(null);
    childRef.current.changeVal(true);
  };

  // const clickCheck = (record) => {
  //   drawerRef.current.setInfo({
  //     schCourseId: record.id,
  //     schCourseName: record.name,
  //   });
  //   drawerRef.current.setVisible(true);
  // };


  const openMenu = (record) => {
    detailRef.current.setInfo({
      schCourseId: record.schCourseId || record.id,
      bizType: 0,
      id: record.id
    })
    detailRef.current.setVisible(true);
  }



  useEffect(() => {
    fetchCourses();
  }, [JSON.stringify(page)]);

  const fetchCourses = () => {
    const info = {
      pageNum: page.pageNum,
      pageSize: page.pageSize,
    };
    getMyLessonsApi(info)
      .then((res) => {
        // console.log(res, 'fetchCourses');
        setCourses(res.data);
      })
      .catch((e) => {
        console.log(e);
      });
  };

  const onPaginationChange = (pageNumber, pageSize) => {
    setPage({
      pageNum: pageNumber,
      pageSize: pageSize,
    });
  };

  const editItemClick = (record) => {
    childRef.current.setUpdateId(record.id);
    childRef.current.setFormData(record);
    childRef.current.changeVal(true);
  };

  const teacherClick = (record) => {
    teacherRef.current.setUpdateId(record.id);
    teacherRef.current.setFormData(record);
    teacherRef.current.changeVal(true);
  };
  const teacherClick1 = (record)=>{
    // console.log(record)
    studentRef.current.setUpdateId(record.id);
    studentRef.current.setFormData(record);
    studentRef.current.changeVal(true);
  }

  const delItemClick = (id) => {
    deleteLessonApi({ id: id })
      .then((res) => {
        console.log(res);1
        Message.success(res.msg);
        fetchCourses();
      })
      .catch((e) => {
        console.log(e);
      });
  };

  return (
    <Card className={styles.container}>
      <Row justify={'end'}>
        <Button
          size="large"
          type="primary"
          onClick={updateChildState}
          style={{ marginBottom: 16 }}
        >
          新建课程
        </Button>
      </Row>
      <Table
        columns={columns}
        data={courses.list}
        pagination={{
          total: courses.total,
          showTotal: true,
          showJumper: true,
          sizeCanChange: true,
          current: page.pageNum,
          onChange: (pageNumber, pageSize) =>
            onPaginationChange(pageNumber, pageSize),
        }}
        pagePosition={'bottomCenter'}
      />
      <LessonFormModal ref={childRef} cancelBackToRefresh={fetchCourses} />
      <TeacherModal ref={teacherRef} cancelBackToRefresh={fetchCourses} />
      <DetailDrawer ref={detailRef} openMenu={openMenu} />
      <Student ref={ studentRef} cancelBackToRefresh={fetchCourses}/>
    </Card>
  );
}

export default Course;
